<template>
    <nav class="nav-buttons">
        <!-- 中间按钮 -->
        <div class="nav-center">
            <RouterLink to="/" class="btn">🏠 首页</RouterLink>
            <RouterLink to="/play" class="btn">🎮 游玩页</RouterLink>
            <RouterLink to="/community" class="btn">👥 社区</RouterLink>
            <RouterLink to="/favorites" class="btn">⭐ 收藏</RouterLink>
        </div>

        <!-- 右上角头像 -->
        <div class="nav-avatar">
            <el-dropdown trigger="hover" @command="handleCommand">
                <span class="avatar-wrapper">
                    <img :src="avatarUrl" class="avatar-img" />
                </span>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                        <el-dropdown-item command="logout">退出</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>
    </nav>
</template>

<script setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { logout } from '@/utils/auth'
import { useUserStore } from '@/store/user' // ✅ 引入 Pinia 用户仓库

const router = useRouter()
const userStore = useUserStore()

// 默认头像或用户设置的头像
const defaultAvatar = new URL('backend/app/static/avatars/default.png', import.meta.url).href
const avatarUrl = computed(() => {
  const avatar = localStorage.getItem('avatar')
  if (avatar) {
    // 如果已经有 http 前缀就不再加
    return avatar.startsWith('http') ? avatar : 'http://localhost:5000' + avatar
  }
  return defaultAvatar
})
// 菜单点击响应
const handleCommand = async (command) => {
    if (command === 'profile') {
        router.push('/profile')
    } else if (command === 'logout') {
        const success = await logout()
        if (success) {
            localStorage.removeItem('avatar')
            userStore.avatar = null
            router.push('/login')
        } else {
            alert('退出失败，请稍后重试')
        }
    }
}
</script>

<style scoped>
.nav-buttons {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1000;
    display: flex;
    justify-content: center;
    padding: 10px;
    background-color: #222;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.nav-center {
    display: flex;
    gap: 10px;
}

.btn {
    background-color: #444;
    color: white;
    padding: 10px 15px;
    border-radius: 6px;
    text-decoration: none;
    transition: background-color 0.2s;
    display: flex;
    align-items: center;
}

.btn:hover {
    background-color: #666;
}

.nav-avatar {
    position: absolute;
    top: 10px;
    right: 30px;
}

.avatar-wrapper {
    cursor: pointer;
    display: inline-block;
}

.avatar-img {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #666;
}
</style>
